package com.zz.common

import java.util.UUID

import scala.concurrent.{ExecutionContext, Future}

import akka.actor.ActorSystem
import com.typesafe.scalalogging.Logger
import com.zz.ady.idl.IdType
import com.zz.common.cassandra.CassandraConfig
import com.zz.common.dao.CassandraDAO
import com.zz.idl.ZidIndex

class ZidScyllaStorage(cassandra: CassandraConfig)(implicit system: ActorSystem, ec: ExecutionContext) extends ZidStorage[Future, String] {

  protected val logger = Logger(getClass)

  protected val dao: CassandraDAO = CassandraDAO(cassandra)

  override def storeIdBundleWithZid(in: ZidIndex): Future[Unit] = dao.putBundle(in.id, in)

  override def queryZids(`type`: IdType, id: String): Future[List[String]] = dao.queryZidsByIdByType(id, `type`)

  override def findBundleByZid(id: String): Future[Option[ZidIndex]] = dao.findZidIndex(id)

  override def storeIdBundleWithoutZid(in: ZidIndex): Future[String] = {
    dao.queryZidsByIdBundle(in) flatMap {
      case x :: Nil =>
        // logger.debug("query: {}, result: {}", in, x)
        val ids = dao.nonEmptyIds(in)
        if (ids.length == 1 && ids.headOption.map(_._2).contains(IdType.IMEI_MD5)) {
          Future.successful(x)
        } else dao.putBundle(x, in).map(_ => x)
      case Nil =>
        //logger.debug("query: {}, result: None", in)
        val zid = UUID.randomUUID().toString
        dao.putBundle(zid, in).map(_ => zid)
      case x :: xs =>
        // logger.debug("query: {}, result: {}", in, x :: xs)
        dao.putBundle(x, in).map(_ => x)
    }
  }
}
